package com.xiyan.mq.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: ruiyanglee
 * @date: 2020-11-09 14:23
 * @description: sender
 */

@RestController
@RequestMapping("/sender")
public class SenderController {

    public static final Logger logger = LoggerFactory.getLogger(SenderController.class);

    @Autowired
    private RabbitTemplate template;

//    @Autowired
//    private Queue queue;

    @Autowired
    private DirectExchange direct;

    AtomicInteger index = new AtomicInteger(0);

    AtomicInteger count = new AtomicInteger(0);

    private final String[] keys = {"error", "info", "warning"};

    // 定时发送消息
//    @Scheduled(fixedDelay = 1000, initialDelay = 500)
    @GetMapping
    public void send() {
        StringBuilder builder = new StringBuilder("Hello to ");
        if (this.index.incrementAndGet() == 3) {
            this.index.set(0);
        }
        String key = keys[this.index.get()];
        builder.append(key).append(' ');
        builder.append(this.count.get());
        this.count.incrementAndGet();
        String message = builder.toString();
        template.convertAndSend(direct.getName(), key, message);
        logger.info(" [x] Sent '" + message + "'");
    }
}
